package com.sgb.kjwl.view.ui.fragment.material;

import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentStList3Binding;
import com.sgb.kjwl.di.material.DaggerMaterialFragComponent;
import com.sgb.kjwl.di.material.MaterialFragModule;
import com.sgb.kjwl.model.entity.STFilterEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.SearchSTEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.MaterialEvent;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.adapter.search.SearchSTAdapter;
import com.sgb.kjwl.view.widget.CCAreaWindow;
import com.sgb.kjwl.view.widget.CommercialConcreteFliterPopWindow3;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.viewmodel.material.STFragListModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

/**
 * Description: 商砼筛选列表改版3
 * Author zhengkewen
 */
public class STListFragment3 extends AppFragment {
    public static String KEY_ID = "id";
    public static String KEY_FID = "fId";
    public static String KEY_POSITION = "position";
    @Inject
    STFragListModel3 viewModel;
    private FragmentStList3Binding binding;
    private SearchSTAdapter adapter;
    private String id;
    private String fId;  //用户筛选类别查询
    private String lon;
    private String lat;
    private DictWindow5 levelWindow5;
    private String levelChecked = "";
    private List<DictEntity3> levelDictEntityList;
    private STFilterEntity stFilterEntity;
    private CCAreaWindow storeMultiWindow4;
    private List<DictEntity3> storeDictEntityList;
    private String distanceChecked = "..";
    private DictWindow5 distanceDistanceWindow5;
    private List<DictEntity3> distanceDictEntityList;
    private CommercialConcreteFliterPopWindow3 popWindow;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private int position;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                adapter.setDatas(null);
                init();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMaterialFragComponent.builder()
                .appComponent(appComponent)
                .materialFragModule(new MaterialFragModule(this))
                .build()
                .inject(this);
    }

    public static STListFragment3 newInstance(String id, String fId, int position) {
        STListFragment3 fragment = new STListFragment3();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_ID, id);
        bundle.putString(KEY_FID, fId);
        bundle.putInt(KEY_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_st_list3, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        id = getArguments().getString(KEY_ID);
        fId = getArguments().getString(KEY_FID);
        position = getArguments().getInt(KEY_POSITION);
        initView();
        if (init && isVisible) {
            init = false;
            adapter.setDatas(null);
            init();
        }
    }

    private void initView() {
        binding.levelLayout.setOnClickListener(this);
        binding.distanceLayout.setOnClickListener(this);
        binding.storeLayout.setOnClickListener(this);
        binding.filterLayout.setOnClickListener(this);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));

        adapter = new SearchSTAdapter(getActivity(), null);
        adapter.setOnItemClick(new AdapterOnItemClick<SearchSTEntity>() {
            @Override
            public void onItemClick(SearchSTEntity searchSTEntity, int position) {
                MaterialFilterJson filterJson = new MaterialFilterJson();
                if (TextUtils.isEmpty(viewModel.materialFilterJson.get().getStrengthId())) {
                    filterJson.setStrengthId(searchSTEntity.getStrengthId());
                } else {
                    filterJson.setStrengthId(viewModel.materialFilterJson.get().getStrengthId());
                }
                filterJson.setGradationId(viewModel.materialFilterJson.get().getGradationId());
                filterJson.setServiceId(viewModel.materialFilterJson.get().getServiceId());

                ConcreteDetailActivity2.start(getActivity(), searchSTEntity.getId(), filterJson);
            }
        });
        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getSTModel(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getSTModel(true);
            }
        });

        popWindow = new CommercialConcreteFliterPopWindow3(getActivity());
        popWindow.setBgView(binding.grayLayout);
        popWindow.setFilterResultClick(new CommercialConcreteFliterPopWindow3.FilterResultClick() {
            @Override
            public void result(MaterialFilterJson materialFilterJson, List<DictEntity3> data, int position) {
                viewModel.materialFilterJson.get().setAreaId(materialFilterJson.getAreaId());
                viewModel.materialFilterJson.get().setStrengthId(materialFilterJson.getStrengthId());
                viewModel.materialFilterJson.get().setGradationId(materialFilterJson.getGradationId());
                viewModel.materialFilterJson.get().setServiceId(materialFilterJson.getServiceId());
                viewModel.materialFilterJson.get().setDistanceId(materialFilterJson.getDistance());
                viewModel.materialFilterJson.get().setPriceSort(materialFilterJson.getPriceSort());
                if (materialFilterJson.getAdmixtureId().size() != 0)
                    viewModel.materialFilterJson.get().setAdmixtureId(materialFilterJson.getAdmixtureId());
                viewModel.getSTModel(false);

                levelChecked = materialFilterJson.getStrengthId();
                levelWindow5.setCheckDefaultById(levelWindow5.getCheckDefultId(levelChecked));

                distanceChecked = materialFilterJson.getDistanceId();
                distanceDistanceWindow5.setCheckDefaultById(distanceDistanceWindow5.getCheckDefultId(distanceChecked));

                storeMultiWindow4.setAreaCheckDefault(data, position);
            }

            @Override
            public void queryTypeChild(String id) {
            }

            @Override
            public void queryNameChild(String id) {
            }
        });

        initFilterView();
    }

    private void initFilterView() {
        levelWindow5 = new DictWindow5(getActivity());
        levelWindow5.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                levelChecked = dictEntity.getId();
                viewModel.materialFilterJson.get().setStrengthId(dictEntity.getId());
                viewModel.getSTModel(false);

                popWindow.setGradeDefault(levelWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            }
        });
        levelWindow5.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.levelArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

        storeMultiWindow4 = new CCAreaWindow(getActivity());
        storeMultiWindow4.setOnCallBack(new CCAreaWindow.OnCallBack() {
            @Override
            public void result(String id, DictEntity3 dictEntity3, int position) {
//                viewModel.materialFilterJson.get().setAreaId(storeIds);
                viewModel.materialFilterJson.get().setAreaId(id);
                viewModel.getSTModel(false);
                popWindow.setAreaDefault(dictEntity3, position);
            }
        });
        storeMultiWindow4.setOnCloseBack(new CCAreaWindow.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.storeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
        distanceDistanceWindow5 = new DictWindow5(getActivity(), 1);
        distanceDistanceWindow5.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                distanceChecked = dictEntity.getId();
                viewModel.materialFilterJson.get().setDistanceId(dictEntity.getName());
//                viewModel.materialFilterJson.get().setDistance(dictEntity.getName());
                viewModel.getSTModel(false);

                popWindow.setDistanceDefault(distanceDistanceWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            }
        });
        distanceDistanceWindow5.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.distanceArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
    }

    private void init() {
//        viewModel.getSTModel(false);
    }

    public void showList(List<SearchSTEntity> list, boolean isLoadMore) {
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.recyclerView.refreshComplete();
            binding.recyclerView.setLoadingMoreEnabled(true);
            adapter.setDatas(list);
        }
    }

    public void showPop(STFilterEntity data) {
        this.stFilterEntity = data;
        if (data == null) {
            return;
        }
        popWindow.setData(data);
        if (data.getStrength() == null || data.getStrength().size() == 0) {
            return;
        }
        this.levelDictEntityList = data.getStrength();
        levelChecked = data.getStrength().get(0).getId();
        levelWindow5.setData(data.getStrength());
        levelWindow5.setCheckDefaultById(levelChecked);
        popWindow.setGradeDefault(levelWindow5.getCheckDefultPosition(levelChecked), levelChecked);
        if (data.getArea() == null || data.getArea().size() == 0) {
            return;
        }
        this.storeDictEntityList = data.getArea();
        storeMultiWindow4.setData(data.getArea());
        if (data.getGradation() == null || data.getGradation().size() == 0) {
            return;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.level_layout:
                binding.levelArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                levelWindow5.setCheckDefaultById(levelChecked);
                levelWindow5.showPopwindow(binding.levelLayout);
                if (levelDictEntityList == null) {
                    viewModel.getSTFilterTypeModel(fId);
                }
                break;
            case R.id.store_layout:
                binding.storeArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                storeMultiWindow4.showPopwindow(binding.storeLayout);
                if (storeDictEntityList == null) {
                    viewModel.getSTFilterTypeModel(fId);
                }
                break;
            case R.id.distance_layout:
                if (distanceDictEntityList == null || distanceDictEntityList.size() == 0) {
                    viewModel.getFilterDistance(fId);
                } else {
                    binding.distanceArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                    distanceDistanceWindow5.setCheckDefaultById(distanceChecked);
                    distanceDistanceWindow5.showPopwindow(binding.distanceLayout);
                }
                break;
            case R.id.filter_layout:
                popWindow.showPopwindow(binding.filterLayout);
                if (stFilterEntity == null) {
                    viewModel.getSTFilterTypeModel(fId);
                }
                break;
        }
    }

    public void showDistancePopWindow(List<DictEntity3> data) {
        this.distanceDictEntityList = data;
        if (data == null || data.size() == 0) {
            Toast.makeText(getActivity(), "该商品分类暂未配置距离筛选值", Toast.LENGTH_SHORT).show();
            return;
        }
        distanceDistanceWindow5.setData(data);
        binding.distanceArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        distanceDistanceWindow5.setCheckDefaultById(distanceChecked);
        distanceDistanceWindow5.showPopwindow(binding.distanceLayout);

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ST_FILTER) {
            String text = (String) event.getMessageData();
            viewModel.materialFilterJson.get().setText(text);
            viewModel.getSTModel(false);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_LOC) {
            lon = (String) event.getObject();
            lat = (String) event.getMessageData();
            viewModel.materialFilterJson.get().setLat(lat);
            viewModel.materialFilterJson.get().setLon(lon);
            if (position == 0)
                viewModel.getSTModel(false);
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent2(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_GOODS_LOC_SELECT) {
            lon = (String) event.getObject();
            lat = (String) event.getMessageData();
            viewModel.materialFilterJson.get().setLat(lat);
            viewModel.materialFilterJson.get().setLon(lon);
            viewModel.getSTModel(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
